package ua.races.dom.command;

import ua.races.dom.analyzerDirector.DocumentAnalyzer;
import org.apache.log4j.Logger;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.util.HashMap;

public class Analyzer {

    private static final Logger log = Logger.getLogger(Analyzer.class.getName());

    public static HashMap<String, String> buildMap() {
        final HashMap<String, String> commands;
        log.info("Building commands Map");

        DOMParser parser = new DOMParser();
        try {
            parser.parse("XMLCommand/commandList.xml");
        } catch (SAXException e) {
            log.error(e);
        } catch (IOException e) {
            log.error(e);
        }
        Document document = parser.getDocument();
        Element root = document.getDocumentElement();

        commands = new HashMap<String, String>();
        NodeList commandNodes = root.getElementsByTagName("command");
        for (int i = 0; i < commandNodes.getLength(); i++) {
            Element commandElement = (Element) commandNodes.item(i);
            commands.put(DocumentAnalyzer.getBabyValue(commandElement, "parameter"),
                    DocumentAnalyzer.getBabyValue(commandElement, "className"));
        }

        log.info("Commands Map was successfully built!");
        return commands;
    }
}
